package ui 
{
	import event.CommEvent;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	/**
	 * ...
	 * @author carlor
	 */
	public class Dialog 
	{
		private var _form: Sprite;
		
		public function Dialog(form: Sprite) 
		{
			_form = form;
			_form.cacheAsBitmap = true;
			_form.addEventListener(Event.ADDED_TO_STAGE, onInit);
		}
		
		public function dispose(): void
		{
			if (_form.parent) _form.parent.removeChild(_form);
			_form = null;
		}
		
		public function get form(): Sprite
		{
			return _form;
		}
		
		public function onInit(e: Event): void
		{
			_form.removeEventListener(Event.ADDED_TO_STAGE, onInit);
			_form.dispatchEvent(new CommEvent(CommEvent.FORM_INIT));
			_form.addEventListener(CommEvent.DIALOG_SHOW, onShow);
			_form.addEventListener(CommEvent.DIALOG_HIDE, onHide);
			_form.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			_form.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		}
		
		private function putScreenCenter(): void
		{
			_form.x = Math.floor((Engine.mainStage.stageWidth - form.width) / 2);
			_form.y = Math.floor((Engine.mainStage.stageHeight - form.height) / 2);
		}
		
		protected function initInterface(): void
		{
			putScreenCenter();
		}
		
		protected function finalInterface(): void
		{
			
		}
		
		public function onShow(e: CommEvent): void
		{
			this._form.visible = true;
			initInterface();
			_form.dispatchEvent(new CommEvent(CommEvent.FORM_SHOW));
		}
		
		public function onHide(e: CommEvent): void
		{
			this._form.visible = false;
			_form.dispatchEvent(new CommEvent(CommEvent.FORM_HIDE));
		}
		
		private function onMouseDown(e: MouseEvent): void
		{
			if (! form.hasOwnProperty("form") || ! (form["form"].hasOwnProperty("CanDrag")) || form["form"]["CanDrag"] == false ) return;
			if ((e.target == form["form"] || e.target.parent == form["form"]) && e.localY < 26) 
				_form.startDrag();
		}
		
		private function onMouseUp(e: MouseEvent): void
		{
			_form.stopDrag();
		}
	}

}